﻿using JetBrains.Annotations;

namespace HurricanePackage
{
    /// <summary>
    /// 单例模板类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Singleton<T> where T : class, new()
    {
        private Singleton()
        {
        }

        //volatile : 保证多线程下对象构造的严格顺序
        private static volatile T g_instance;
        // 用于lock块的对象
        [NotNull] private static readonly object g_synclock = new object();

        public static T Instance
        {
            get
            {
                if (g_instance == null)
                {
                    lock (g_synclock)
                    {
                        if (g_instance == null)
                        {
                            // 若T class具有私有构造函数,那么则无法使用SingletonProvider<T>来实例化new T();
                            g_instance = new T();
                        }
                    }
                }
                return g_instance;
            }
            set { g_instance = value; }
        }
    }


    //另一种单例写法
    public class Singleton_1
    {
        public static readonly Singleton_1 instance;
        //等效于在静态构造器中声明
       // public static readonly Singleton_1 instance = new Singleton_1();

        //在静态字段被访问之前会先访问静态构造器
        //静态构造器可以保证在多线程情况下只有一个线程执行,相当于IL的自动加锁
        //但是静态的构造器不支持参数话
        static Singleton_1()
        {
            instance = new Singleton_1();
        }
        
        private Singleton_1(){}
        
    }
    
}